package net.wicp.tams.common.connector.annotation.spring.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.common.Result;
import net.wicp.tams.common.apiext.StringUtil;
import net.wicp.tams.common.connector.beans.CusDynaBean;
import net.wicp.tams.common.connector.executor.IBusiApp;
import net.wicp.tams.common.connector.executor.impl.CommonService;
import net.wicp.tams.common.exception.ProjectException;

/***
 * 清除缓存
 * 
 * @author zhoujunhui
 */
@Service(value = "connector.cache")
@Slf4j
public class ConnectorCache implements IBusiApp {

	@Autowired
	private CommonService commonService;

	@Override
	public CusDynaBean exe(CusDynaBean inputBean, CusDynaBean outBeanOri) throws ProjectException {
		Cmd cmd = inputBean.getByType(Cmd.class, "cmd");
		String appkey = inputBean.getStrValueByName("appkey");
		if ((cmd == Cmd.add || cmd == Cmd.del) && StringUtil.isNull(appkey)) {
			outBeanOri.setResult(Result.getError("add和del需要传入appkey"));
			return outBeanOri;
		}
		switch (cmd) {
		case add:
			Integer expire = (Integer) inputBean.get("expire");
			commonService.needCacheMap.put(appkey, expire);
			break;
		case del:
			commonService.needCacheMap.remove(appkey);
			break;
		case clean:
			commonService.needCacheMap.clear();
			break;
		case query:
			Set<String> keySet = commonService.needCacheMap.keySet();
			List<CusDynaBean> inputlist = new ArrayList<>();
			for (String key : keySet) {
				CusDynaBean tempbean = outBeanOri.newCusDynaBean("caches");
				tempbean.set("appkey", key);
				tempbean.set("expire", commonService.needCacheMap.get(key));
				inputlist.add(tempbean);
			}
			outBeanOri.set("caches", inputlist);
			break;
		default:
			break;
		}
		outBeanOri.setResult(Result.getSuc());
		log.info("缓存已更新");
		return outBeanOri;
	}
}
